package edu.mju.controller;

import com.alibaba.fastjson.JSONObject;
import edu.mju.dao.IRoutesDao;
import edu.mju.dao.impl.RoutesDaoImpl;
import edu.mju.entity.Order;
import edu.mju.entity.TouristRoutes;
import edu.mju.service.IOrderService;
import edu.mju.service.IRoutesService;
import edu.mju.service.impl.OrderServiceImpl;
import edu.mju.service.impl.RoutesServiceImpl;
import edu.mju.util.FileUtil;
import edu.mju.util.Pager;
import edu.mju.util.RequestStrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author:wyp
 * @Date:2020/5/29 20:57
 */
@WebServlet("/routesController")
public class RoutesController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一编码，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        //获取method
        String method = req.getParameter("method");
        System.out.println("doget:"+method);
        if("routesList".equals(method)){
            //对应backindex.jsp的：旅游线路列表
            req.getRequestDispatcher("/WEB-INF/view/backindex/routes-list.jsp").forward(req,resp);
        }else if("routesByTouristId".equals(method)){
            String touristId = req.getParameter("touristId");
            req.getRequestDispatcher("/WEB-INF/view/backindex/routes-edit.jsp?touristId="+touristId).forward(req,resp);
        }else if("routesEdit".equals(method)){
            String touristId = req.getParameter("touristId");
            req.getRequestDispatcher("/WEB-INF/view/company/routes-edit.jsp?touristId="+touristId).forward(req,resp);
        }else if("allRoutesByCompanyId".equals(method)){
            String companyId = req.getParameter("companyId");
            req.getRequestDispatcher("/WEB-INF/view/company/routes-list.jsp?companyId="+companyId).forward(req,resp);
        }else if("routesDetail".equals(method)){
            //通过该方法，取得session的userid值
            String touristId = req.getParameter("touristId");
            String userId = String.valueOf(req.getSession().getAttribute("userId"));
            if(userId!=null && !"null".equals(userId)){
                resp.sendRedirect("./routesDetail.jsp?touristId="+touristId+"&userId="+userId);
            }else {
                resp.sendRedirect("./routesDetail.jsp?touristId="+touristId+"&userId=null");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一编码，防止中文乱码

        resp.setContentType("text/html;charSet=utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        //获取method
        String method = req.getParameter("method");
        System.out.println("dopost:"+method);
        if("routesfindList".equals(method)){
            //对应routesList.jsp ：根据景点名线路分页 routesPagerBySpotName()
            routesfindList(req, resp);
        }else if("routesList".equals(method)){
            //对应routesList.jsp : 查找所有线路 routesPager()
            pagernate(req,resp);
        }else if("userOrder".equals(method)){
            pagernateOrder(req,resp);
        }else if("searchRoutes".equals(method)){
            //对应company>routes-list.jsp的查询按钮
            searchRoutes(req,resp);
        }else if("orderAdd".equals(method)){
            //对应routesDeatail.jsp的立即预约按钮事件
            orderAdd(req,resp);
        }else if("routesUpdate".equals(method)){
            //对应routes-edit.jsp ：更新操作
            routesUpdate(req,resp);
        }else if("routesAdd".equals(method)){
            //对应routes-add.jsp ：新增操作
            routesAdd(req,resp);
        }else if("routesListByCompanyId".equals(method)){
            //对应company-route-list.jsp 页面载入数据
            pagernateRoutesList(req, resp);
        }else if("routesDetail".equals(method)){
            //对应routesDetail.jsp的获取线路信息
            routesDetail(req,resp);
        }else if("routesById".equals(method)){
            //对应company>routes-edit.jsp的通过id查找景点信息
            routesById(req,resp);
        }else if("routesDelete".equals(method)){
            //对应company/backindex>routes-list.jsp的删除按钮
            routesDel(req,resp);
        }

    }

    /**
     *  删除线路
     * @param req
     * @param resp
     */
    private void routesDel(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Integer touristId =RequestStrUtil.getValue(req.getParameter("touristId"),0);
            IRoutesService routesService = new RoutesServiceImpl();
            boolean delRoutes = routesService.delete(touristId);
            if(delRoutes) {
                //删除图片
                String imgUrl = req.getParameter("imgUrl");
                String delPath = this.getServletContext().getRealPath(imgUrl);
                FileUtil.deleteFile(delPath);

                String result = JSONObject.toJSONString(delRoutes);
                System.out.println(result);
                resp.getWriter().write(result);
            }else {
                //只要返回的不是json格式，ajax执行error
                resp.getWriter().write("删除失败！");
            }

        }catch (Exception e){
            System.out.println("routesDel方法捕获异常");
            e.printStackTrace();
        }
    }

    /**
     *  根据线路ID查找
     * @param req
     * @param resp
     */
    private void routesById(HttpServletRequest req, HttpServletResponse resp) {
        //获取ID
        Integer touristId = RequestStrUtil.getValue(req.getParameter("touristId"),0);

        try {
            IRoutesService routesService = new RoutesServiceImpl();
            TouristRoutes getResult =  routesService.findByRoutesId(touristId);

            String result = JSONObject.toJSONString(getResult);
            System.out.println(result);

            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据线路ID获取详细信息
     * @param req
     * @param resp
     */
    private void routesDetail(HttpServletRequest req, HttpServletResponse resp){
        Integer touristId = RequestStrUtil.getValue(req.getParameter("touristId"),0);
        TouristRoutes routes = null;
        IRoutesService routesService = new RoutesServiceImpl();
        routes = routesService.findByRoutesId(Integer.valueOf(touristId));

        String result = JSONObject.toJSONString(routes);
        try {
            resp.getWriter().write(result);
        }catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *  用于各个旅游公司的线路展示
     * 分页查询旅游公司所开设的路线
     * @param req
     * @param resp
     */
    private void pagernateRoutesList(HttpServletRequest req, HttpServletResponse resp){
        //每页显示数据
        int pageSize = 10 ;
        //设定默认当前页码数
        int page = 1;
        Integer getcompanyId =RequestStrUtil.getValue(req.getParameter("companyId"),0);
        String getPage = req.getParameter("page");
        if(getPage !=null && ! "".equals(getPage)){
            page = (Integer.valueOf(getPage)) ;
        }

        TouristRoutes touristRoutes = new TouristRoutes();
        touristRoutes.setTouristCompanyId(getcompanyId);
        IRoutesService routesService = new RoutesServiceImpl();
        Pager pager = routesService.pagernate(page,pageSize,touristRoutes);
        req.getSession().setAttribute("pager",pager);

        String result = JSONObject.toJSONString(pager);
        System.out.println("pagernate的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }


    /**
     *  添加景点
     * @param req
     * @param resp
     */
    private void routesAdd(HttpServletRequest req, HttpServletResponse resp){
        try {
            //获取登陆时设置的session中的companyId
            Integer companyId = (Integer) req.getSession().getAttribute("companyId");

            String allSpot=req.getParameter("allSpot");
            String restaurant=req.getParameter("restaurant");
            String live = req.getParameter("live");
            String traffice = req.getParameter("traffice");
            String touristTime = req.getParameter("touristTime");
            Integer touristPrice =RequestStrUtil.getValue(req.getParameter("touristPrice"),0);
            String tel = req.getParameter("tel");
            Integer maxPeople =RequestStrUtil.getValue(req.getParameter("maxPeople"),0);
            String routesImg = req.getParameter("routesImg");

            TouristRoutes inroutes = new TouristRoutes(allSpot,restaurant,live,traffice,touristTime,touristPrice,tel,companyId,maxPeople,routesImg);
            IRoutesDao routesDao = new RoutesDaoImpl();
            boolean Isinsert = routesDao.insert(inroutes);
            if(Isinsert) {
                String result = JSONObject.toJSONString(Isinsert);
                System.out.println(result);
                resp.getWriter().write(result);
            }else {
                //只要返回的不是json格式，ajax执行error
                resp.getWriter().write("添加失败！");
            }

        }catch (Exception e){
            System.out.println("routesAdd方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *  更新数据
     * @param req
     * @param resp
     */
    private void routesUpdate(HttpServletRequest req, HttpServletResponse resp) {
        Integer touristId =RequestStrUtil.getValue(req.getParameter("touristId"),0);
        String allSpot = req.getParameter("allSpot");
        String restaurant = req.getParameter("restaurant");
        String live = req.getParameter("live");
        String traffice = req.getParameter("traffice");
        String touristTime = req.getParameter("touristTime");
        Integer touristPrice =RequestStrUtil.getValue(req.getParameter("touristPrice"),0);
        String tel = req.getParameter("tel");
        Integer maxPeople = RequestStrUtil.getValue(req.getParameter("maxPeople"),0);
        String routesImg = req.getParameter("routesImg");

        TouristRoutes routes = new TouristRoutes(touristId,allSpot,restaurant,live,traffice,touristTime,touristPrice,tel,maxPeople,routesImg);
        IRoutesService routesService = new RoutesServiceImpl();
        try {
            if(routesService.update(routes)){
                String rs = JSONObject.toJSONString(routes);
                resp.getWriter().write(rs);
            }else {
                resp.getWriter().write("false");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *  预约成功，自动向TouristRoutes的nowPeople + 1;
     * @param req
     * @param resp
     */
    private void orderAdd(HttpServletRequest req, HttpServletResponse resp){
        try {
            String getUserId =String.valueOf(req.getSession().getAttribute("userId"));
            Integer touristId = RequestStrUtil.getValue(req.getParameter("touristId"),0);
            Integer userId = RequestStrUtil.getValue(getUserId,0);
            Integer touristCompanyId = RequestStrUtil.getValue(req.getParameter("touristCompanyId"),0);

            Order order = null;
            if(touristCompanyId!=0 && userId!=0 && touristCompanyId!=0){
                order = new Order(userId,touristId,touristCompanyId);
            }
            IOrderService  orderService =new OrderServiceImpl();
            boolean Isinsert = orderService.insert(order);
            if(Isinsert) {
                String result = JSONObject.toJSONString(Isinsert);
                System.out.println(result);
                resp.getWriter().write(result);
            }else {
                //只要返回的不是json格式，ajax执行error
                resp.getWriter().write("添加失败！");
            }

        }catch (Exception e){
            System.out.println("routesAdd方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *  旅游公司查找旅游线路
     * @param req
     * @param resp
     */
    private void searchRoutes(HttpServletRequest req, HttpServletResponse resp){
        //每页显示数据
        Integer pageSize = RequestStrUtil.getValue(req.getParameter("pageSize"),5);



        String name = req.getParameter("name");
        Integer companyId = (Integer) req.getSession().getAttribute("companyId");

        //设定默认当前页码数
        Integer page = RequestStrUtil.getValue(req.getParameter("page"),1);


        TouristRoutes touristRoutes = new TouristRoutes();
        touristRoutes.setAllSpot(name);
        touristRoutes.setTouristCompanyId(companyId);

        IRoutesService routesService = new RoutesServiceImpl();
        Pager pager = routesService.pager(page,pageSize,touristRoutes);
        req.getSession().setAttribute("pager",pager);

        String result = JSONObject.toJSONString(pager);
        System.out.println("pagernate的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     * 查找订单
     * @param req
     * @param resp
     */
    private void pagernateOrder(HttpServletRequest req, HttpServletResponse resp){

        Integer userId = (Integer) req.getSession().getAttribute("userId");
        System.out.println("userId:"+userId);
        //每页显示数据
        int pageSize = 10 ;
        //设定默认当前页码数
        Integer page = RequestStrUtil.getValue(req.getParameter("page"),1);


        IOrderService orderService = new OrderServiceImpl();
        Pager pager = orderService.findByUserId(page,pageSize,userId);

        req.getSession().setAttribute("pager",pager);

        String result = JSONObject.toJSONString(pager);
        System.out.println("pagernate的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *      分页查询所有线路信息
     * @param req
     * @param resp
     */
    public void pagernate(HttpServletRequest req, HttpServletResponse resp){
        //每页显示数据
        Integer pageSize = RequestStrUtil.getValue(req.getParameter("pageSize"),5);

        //设定默认当前页码数
        Integer page = RequestStrUtil.getValue(req.getParameter("page"),1);

        TouristRoutes touristRoutes = new TouristRoutes();


        IRoutesService routesService = new RoutesServiceImpl();
        Pager pager = routesService.pagernate(page,pageSize,touristRoutes);
        req.getSession().setAttribute("pager",pager);

        String result = JSONObject.toJSONString(pager);
        System.out.println("pagernate的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *  查找所有线路信息
     * @param req
     * @param resp
     */
    private void routesfindList(HttpServletRequest req, HttpServletResponse resp){
        //每页显示数据
        Integer pageSize = RequestStrUtil.getValue(req.getParameter("pageSize"),5);

        //设定默认当前页码数
        Integer page = RequestStrUtil.getValue(req.getParameter("page"),1);


        String name = req.getParameter("name");
        String time = req.getParameter("time");
        String price = req.getParameter("price");
        Integer getprice ;
        if("".equals(price) || price==null || "null".equals(price)){
            getprice = null;
        }else {
            getprice = Integer.valueOf(price);
        }



        TouristRoutes touristRoutes = new TouristRoutes();
        touristRoutes.setAllSpot(name);
        touristRoutes.setTouristTime(time);
        touristRoutes.setTouristPrice(getprice);

        IRoutesService routesService = new RoutesServiceImpl();
        Pager pager = routesService.pager(page,pageSize,touristRoutes);
        req.getSession().setAttribute("pager",pager);

        String result = JSONObject.toJSONString(pager);
        System.out.println("pagernate的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }
}
